package com.zheng.api.server.service;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaTemplateData;
import cn.binarywang.wx.miniapp.bean.WxMaTemplateMessage;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.zheng.api.common.constant.ApiConstant;
import com.zheng.api.common.constant.ApiResult;
import com.zheng.api.common.constant.ApiResultConstant;
import com.zheng.api.server.service.base.um.Base4UmbrellaService;
import com.zheng.business.dao.model.BusinessOrderUmbrellaConsumption;
import com.zheng.common.constant.Constant;
import com.zheng.common.util.*;
import com.zheng.umbrella.dao.model.*;
import com.zheng.umbrella.rpc.api.UmbrellaHardwareCommunicationfailLogService;
import com.zheng.umbrella.rpc.api.UmbrellaHardwareMachineService;
import com.zheng.umbrella.rpc.api.UmbrellaHardwarePathService;
import com.zheng.upms.rpc.api.UpmsDictService;
import com.zheng.upms.rpc.api.UpmsSystemParamService;
import com.zheng.wechat.mp.dao.model.WechatMpGzuser;
import com.zheng.wechat.mp.dao.model.WechatMpWebJwid;
import com.zheng.wechat.mp.dao.model.WechatMpWxappfrommessage;
import com.zheng.wechat.mp.dao.model.WechatMpWxapptempletecfg;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Service("wxTemplateService")
public class WxTemplateService extends Base4UmbrellaService {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(WxTemplateService.class);
    @Autowired
    UpmsDictService upmsDictService;
    /**
     * 借伞成功通知
     */
    static final String UM_BORROW_SUCCESS = "KtJXBkFhO623r0fhHsslUZDOrBPP3ac7gxZZMTDpXP4";
    /**
     * 还伞成功通知
     */
    static final String UM_RETURN_SUCCESS = "pa8fCevqPg2GbxUv5TGyknSYfjfY6qAnVbrfLjbrE24";
    /**
     * 还伞提醒
     */
    static final String UM_RETURN_TIPS = "ZTG_u1pu5BrfO9f4R0mcDoxBOe6ACA7AIrAIgvXnaUQ";

    /**
     * 颜色代码
     */
    static final String COLOR_RED     = "#FF0000"; //纯红:
    static final String COLOR_GREED   = "#00FF00"; //绿色:
    static final String COLOR_BLUE    = "#0000FF"; //蓝色:
    static final String COLOR_YELLOW  = "#FFFF00"; //黄色:
    static final String COLOR_SKYBLUE = "#CCEEFF";//天蓝色:

    String UM_WXMINIAPP_MAP_PAGE = "/pages/map";

    /**
     * 微信小程序服务提醒推送
     * @param orderNo
     * @param type
     * @return
     */
    @Async("threadPoolTaskExecutor")
    public void miniAppTemplatePush(String orderNo, Integer type) {
       try {
           //查询订单
           BusinessOrderUmbrellaConsumption consumption = super.baseSelectBusinessOrderUmbrellaConsumptionByOrderNo(orderNo);
           if (consumption == null) {
               return;
           }
           //查询有效formId
           WechatMpWxappfrommessage wechatMpWxappfrommessage = super.baseSelectWechatMpWxappfromIdByUserId(consumption.getUserid());
           if (wechatMpWxappfrommessage == null) {
               return;
           }
           //查询用户
           WechatMpGzuser wechatMpGzuser = super.baseSelectWechatMpGzuser(consumption.getUserid(), false);
           if (wechatMpGzuser == null) {
               return;
           }
           //查询公号配置
           WechatMpWebJwid wechatMpWebJwid = super.baseSelectWechatMpWebJwidByJwid(wechatMpGzuser.getJwid());
           if (wechatMpWebJwid == null) {
               return;
           }
           //查询模板id
           WechatMpWxapptempletecfg wechatMpWxapptempletecfg = super.baseSelectWechatMpWxapptempletecfgByJwidAndType(wechatMpGzuser.getJwid(),type.toString());
           if (wechatMpWxapptempletecfg == null) {
               return;
           }
           //查询租金规则
           UmbrellaRuleRent rent = super.baseSelectUmbrellaRuleRentNoCache(consumption.getRentRuleId(),false);
           if (rent == null) {
               return;
           }


           //1,配置小程序信息
           WxMaDefaultConfigImpl wxConfig = new WxMaDefaultConfigImpl();
           wxConfig.setAppid(wechatMpWebJwid.getWeixinAppid());//小程序appid
           wxConfig.setSecret(wechatMpWebJwid.getWeixinAppsecret());//小程序AppSecret

           WxMaService wxMaService = new WxMaServiceImpl();
           wxMaService.setWxMaConfig(wxConfig);

           //2,设置模版信息（keyword1：类型，keyword2：内容）
           List<WxMaTemplateData> templateDataList = new ArrayList<>();
           String templateId = null;
           if (type == 1) {
               //借伞成功通知
               /**
                * 借伞成功通知
                * 订单编号
                * {{keyword1.DATA}}
                * 借伞地点
                * {{keyword2.DATA}}
                * 借伞日期
                * {{keyword3.DATA}}
                * 伞号
                * {{keyword4.DATA}}
                * 备注
                * {{keyword5.DATA}}
                */
               templateId = wechatMpWxapptempletecfg.getTemplateid();
               if(StringUtils.isEmpty(templateId)){templateId = UM_BORROW_SUCCESS;}
               WxMaTemplateData data1 = new WxMaTemplateData("keyword1", consumption.getOrderno());
               templateDataList.add(data1);
               WxMaTemplateData data2 = new WxMaTemplateData("keyword2", consumption.getRentAdress());
               templateDataList.add(data2);
               WxMaTemplateData data3 = new WxMaTemplateData("keyword3", DateUtil.date2Str(consumption.getBegintime()));
               templateDataList.add(data3);
               WxMaTemplateData data4 = new WxMaTemplateData("keyword4", consumption.getChipNumber());
               templateDataList.add(data4);

               String dictText = upmsDictService.queryDataDictTextByValue(Constant.UM_RULE_TYPE,rent.getChargetype().toString());
               String freeDictText = upmsDictService.queryDataDictTextByValue(Constant.UM_RULE_TYPE,rent.getFreetimetype().toString());
               StringBuffer ruleTrans = new StringBuffer();
               ruleTrans.append("收费标准：").append("￥").append(rent.getPrice()).append("/").append(rent.getChargelength()).append(dictText);
               if(rent.getFreetimelength()>0) {
                   ruleTrans.append("，免费时长：").append(rent.getFreetimelength()).append(freeDictText);
               }
               ruleTrans.append("，不足").append(rent.getChargelength()).append(dictText).append("按").append(rent.getChargelength()).append(dictText).append("计。");
               if(consumption.getLimitamount() != null && consumption.getLimitamount().compareTo(BigDecimal.ZERO) == 1){
                   double f1 = consumption.getLimitamount().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                   ruleTrans.append("封顶金额").append(f1).append("元。");
               }
               if(consumption.getAutoendtime() != null) {
                   ruleTrans.append("最晚还伞日：").append(DateUtil.date2Str(consumption.getAutoendtime())).append("。");
               }
               ruleTrans.append("使用费用将从余额或预付金中扣除，归还雨伞后，预付金将自动退还。(如有疑问请点击下方进入[疑问指南]或直接电联客服号)");

               //order.put("duration",DateUtil.covertIntervalDDHHMI(consumption.getBegintime(),nowDate));
               WxMaTemplateData data5 = new WxMaTemplateData("keyword5", ruleTrans.toString(),COLOR_RED);
               templateDataList.add(data5);

           }else if(type == 2){
             //还伞成功通知
             /** 订单编号
               * {{keyword1.DATA}}
               * 归还地点
               * {{keyword2.DATA}}
               * 归还时间
               * {{keyword3.DATA}}
               * 租借时长
               * {{keyword4.DATA}}
               * 借伞费用
               * {{keyword5.DATA}}
               */
               if(consumption.getAutoendtime() == null ){
                   return;
               }
               templateId = wechatMpWxapptempletecfg.getTemplateid();
               if(StringUtils.isEmpty(templateId)){templateId = UM_RETURN_SUCCESS;}
               WxMaTemplateData data1 = new WxMaTemplateData("keyword1", consumption.getOrderno());
               templateDataList.add(data1);
               WxMaTemplateData data2 = new WxMaTemplateData("keyword2", consumption.getReturnAdress());
               templateDataList.add(data2);
               WxMaTemplateData data3 = new WxMaTemplateData("keyword3", DateUtil.date2Str(consumption.getEndtime()));
               templateDataList.add(data3);
               WxMaTemplateData data4 = new WxMaTemplateData("keyword4", DateUtil.covertIntervalDDHHMI(consumption.getBegintime(),consumption.getEndtime()));
               templateDataList.add(data4);
               WxMaTemplateData data5 = new WxMaTemplateData("keyword5", consumption.getPayamount()+"元");
               templateDataList.add(data5);
           }else if(type == 3){
              //还伞提醒
              /**
                * 订单编号
                *订单编号
                *{{keyword1.DATA}}
                *雨伞编号
                *{{keyword2.DATA}}
                *最晚还伞日
                *{{keyword3.DATA}}
                *待付金额
                *{{keyword4.DATA}}
                *备注
                *{{keyword5.DATA}}
                */
               templateId = wechatMpWxapptempletecfg.getTemplateid();
               if(StringUtils.isEmpty(templateId)){templateId = UM_RETURN_TIPS;}
               WxMaTemplateData data1 = new WxMaTemplateData("keyword1", consumption.getOrderno());
               templateDataList.add(data1);
               WxMaTemplateData data2 = new WxMaTemplateData("keyword2", consumption.getChipNumber());
               templateDataList.add(data2);

               if(consumption.getAutoendtime() != null) {
                   //业务处理最晚还伞时间需+1，取凌晨0点
                   WxMaTemplateData data3 = new WxMaTemplateData("keyword3",
                           DateUtil.date2Str(DateUtil.addDate(consumption.getAutoendtime(), 1),DateUtil.FORMAT_YYYY_MM_DD),COLOR_RED);
                   templateDataList.add(data3);
               }else{
                   WxMaTemplateData data3 = new WxMaTemplateData("keyword3", "无");
                   templateDataList.add(data3);
               }
               DecimalFormat df = new DecimalFormat("0.00");
               WxMaTemplateData data4 = new WxMaTemplateData("keyword4", df.format(super.calculateOrderCost(consumption,rent)));
               templateDataList.add(data4);

               //String dictText = upmsDictService.queryDataDictTextByValue(Constant.UM_RULE_TYPE,rent.getChargetype().toString());
               //String freeDictText = upmsDictService.queryDataDictTextByValue(Constant.UM_RULE_TYPE,rent.getFreetimetype().toString());
               StringBuffer ruleTrans = new StringBuffer();
               //ruleTrans.append("收费标准：").append("￥").append(rent.getPrice()).append("/").append(rent.getChargelength()).append(dictText);
               //if(rent.getFreetimelength()>0) {
               //    ruleTrans.append("，免费时长：").append(rent.getFreetimelength()).append(freeDictText);
               //}
               //ruleTrans.append("，不足").append(rent.getChargelength()).append(dictText).append("按").append(rent.getChargelength()).append(dictText).append("计。");
               //ruleTrans.append("使用费用将从余额或预付金中扣除，归还雨伞后，预付金将自动退还。(如有疑问请点击下方进入[疑问指南]或直接电联客服号)");

               if(consumption.getAutoendtime() != null) {
                   ruleTrans.append("若超过最晚还伞日仍未归还雨伞，系统将自动结束订单并扣除预付金或失效有效时长卡。");
               }else{
                   ruleTrans.append("无。");
               }

               WxMaTemplateData data5 = new WxMaTemplateData("keyword5", ruleTrans.toString(),COLOR_RED);
               templateDataList.add(data5);

            }else if(type == 4){
               //自动结束订单通知,模板库暂时不支持

           }else {
               return;
           }
           //跳转页
           String mainPage = wechatMpWebJwid.getMainpage();
           if (StringUtils.isEmpty(mainPage)){mainPage = UM_WXMINIAPP_MAP_PAGE;}

            //3，设置推送消息
            WxMaTemplateMessage templateMessage = WxMaTemplateMessage.builder()
                    .toUser(wechatMpGzuser.getOpenid())//要推送的用户openid
                    .formId(wechatMpWxappfrommessage.getFormid())//收集到的formid
                    .templateId(templateId)//推送的模版id（在小程序后台设置）
                    .data(templateDataList)//模版信息
                    .page(mainPage)//要跳转到小程序那个页面
                    .build();

            //4，发起推送
            wxMaService.getMsgService().sendTemplateMsg(templateMessage);

            //5，保存数据
           super.updatetWechatMpWxappfromIdById(wechatMpWxappfrommessage.getId(),0,wechatMpWxappfrommessage.getUsetimes(),JsonUtil.object2Json(templateDataList));

        } catch (WxErrorException e) {
            logger.error("推送异常：" + e);
        }
    }
}
